/**
 * Created by jackliu on 15/12/16.
 */

var common = require('../../common');
var pool = require('../index');
var mysql = require('mysql');
var ItbBaseModel = require('./ItbBaseModel');


// Schema 结构
var ItbPartnerCustModel = function(obj){
    ItbBaseModel.call(this,obj);

  // 以下为表定义数据，需要的字段就填入
  //  `pc_id` bigint(20) unsigned NOT NULL AUTO_INCREMENT COMMENT 'id',
  //`partner_id` bigint(20) NOT NULL COMMENT '合伙人id',
  //`user_id` bigint(20) NOT NULL COMMENT '客户的用户id',
  //`start_time` datetime NOT NULL COMMENT '有效开始日期',
  //`end_time` datetime NOT NULL COMMENT '有效结束日期',
  //`create_time` datetime NOT NULL,
  //`update_time` datetime NOT NULL,
  //`update_by` varchar(50) NOT NULL DEFAULT '',
  //`del_flg` int(1) NOT NULL DEFAULT '0' COMMENT '删除flg',



};
ItbPartnerCustModel.prototype = new ItbBaseModel();

// 取得表名
ItbPartnerCustModel.prototype.getTableName = function(){
    return 'itb_partner_cust';
}
// 取得查询语句中where 后面匹配主键的条件（需要各派生类进行重载）
ItbPartnerCustModel.prototype.getWhereConditionOfKeyEqual = function(){
    return 'id='+this.id;
}



//------------------------------------------------------------------
/*
 * 将用户对应的user加为合伙人的下线
 * 参数 partnerUID: 合伙人用户id
 * 参数 mobile: 抽奖人手机号
 * 参数 callback，返回参数：
 *          error:
 *          pc_id:下线纪录的id
 * */
ItbPartnerCustModel.prototype.addPartnerCustom = function(partnerUID, mobile, callback){
    var year = 3; // year

    pool.pool.getConnection(function(err, connection) {
        // Use the connection
        var sql =
            ' insert into `itb_partner_cust`(partner_id, user_id, start_time, end_time, create_time, update_time, update_by)  '+
            ' select * from ( '+
            ' 	select 	(select distinct p.`partner_id` from `itb_partner` p where p.`user_id`='+partnerUID+' and p.`del_flg`=0) as partner_id,  '+
            ' 			(select u.user_id from itb_user u where u.mobile='+mobile+' and u.del_flg=0 limit 0,1) as user_id,  '+
            ' 			sysdate() as start_time, date_add(sysdate() , interval '+year+' year) as end_time, sysdate() as create_time,sysdate() as update_time,'+partnerUID+' as update_by '+
            ' ) m '+
            ' where m.`partner_id` is not null '+
            ' and m.`user_id` is not null ';

        console.log(sql);
        connection.query(sql, function(error, result) {
            // And done with the connection.
            connection.release();

            if(error){
                console.log(sql);
                return callback(error, null);
            }
            if(!result){
                return callback(error, null);
            }
            return callback(error, result.insertId);
        });
    });
};


//--------------------------------end-------------------------------

// 导出
module.exports = ItbPartnerCustModel;